<?php
declare(strict_types=1);

namespace App\Controller\Chat;

use App\Constants\StatusCode;
use App\Controller\AbstractController;
use App\Model\Auth\User;
use App\Model\Chat\Circle;
use App\Model\Chat\FriendApply;
use App\Service\Chat\FriendService;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use App\Middleware\AuthMiddleware;
use App\Service\Auth\UserService;


/**
 * 好友模块
 * Class FriendController
 * @Controller(prefix="chat/friend")
 */
class FriendController extends AbstractController
{

    /**
     * 搜索好友
     * @RequestMapping(path="search", methods="post")
     * @Middlewares({
     *     @Middleware(AuthMiddleware::class),
     * })
     */
    public function search()
    {
        $keyword = $this->request->input('keyword');
        $users = User::query()->where('username', 'like', $keyword . '%')->orWhere('nickname', 'like', $keyword . '%')
            ->select(['id', 'username', 'avatar', 'nickname'])->get()->each(function ($item) {
                $item->nickname = $item->nickname ?: $item->username;
                return $item;
            })->toArray();
        return $this->success(['list' => $users, 'is_type' => '0']);
    }

    /**
     * 用户信息
     * @RequestMapping(path="userInfo", methods="post")
     * @Middlewares({
     *     @Middleware(AuthMiddleware::class),
     * })
     */
    public function userInfo()
    {
        $post_data = $this->request->post();
        if (!isset($post_data['user_id']) || $post_data['user_id'] == '') {
            return $this->error(400, '数据有误');
        }
        $user_id=$post_data['user_id']*1;
        if (!($user_data = UserService::getInstance()->getByUid($user_id))) {
            return $this->error(400, '没有这个用户');
        }
        $is_friend = 0;
        $circle = [];
        $mobile = $user_data['mobile'];
        $from = '';
        $user_info = context_get('user_info');
        $friend_data=FriendService::getInstance()->getFriend($user_info['id'],$user_id);
        if ($user_id == $user_info['id'] || $friend_data) {
            $is_friend = 1;
            if ($friend_data) {
                $from = $friend_data['from'];
            }
            /** 这里获取朋友圈最近的照片 */
            $circle_data = Circle::query()->select(['id','images'])
                ->where([
                    'user_id' => $user_id,
                    'type' => 0
                ])->orderBy('id', 'DESC')
                ->limit(30)->get()->toArray();

            if (count($circle_data)) {
                foreach ($circle_data as $key => $value) {
                    $images=json_decode($value['images']);
                    foreach ($images as $item) {
                        $circle[] = $item['url'];
                        if (count($circle) > 4) {
                            break;
                        }
                    }
                    if (count($circle) > 4) {
                        break;
                    }
                }
            }
        }
        /** 这里是朋友添加 */
        $apply_info = '';
        $apply_id = 0;
        if (isset($post_data['from']) && $post_data['from'] == 'apply_list'){
            $friend_apply_data = FriendApply::query()->select('id,apply_info,from')
                ->where([
                    'friend_id' => $user_info['id'],
                    'user_id' => ($user_id * 1),
                ])
                ->orderBy('id', 'DESC')
                ->first();
            if ($friend_apply_data) {
                $apply_info = $friend_apply_data->content;
                $from = $friend_apply_data->from;
                $apply_id = $friend_apply_data->id;
            }
        }

        $return_data['err'] = 0;
        $return_data['msg'] = 'success';

        $return_data= [
            'user_id' => $user_id,
            'nickname' => $user_data['nickname'],
            'is_friend' => $is_friend,
            'doodling' => $user_data['doodling']??'',
            'avatar' => $user_data['avatar'],
            'show_friend' => [
                'circle' => $circle,
                'mobile' => $mobile,
            ],
            //['搜索登陆名添加', '搜索手机号码添加', '搜索邮箱添加', '扫码添加', '系统默认添加']
            'from' => $from,
            'apply_info' => $apply_info,
            'sex' => $user_data['sex'],
            'apply_id' => $apply_id,
            'username'=>$user_data['username'],
        ];
        return $this->success($return_data);
    }
    /** 通过好友申请 */
    public function confirmApply()
    {
        $post_data = Request::post();
        $return_data = [
            'err' => 1,
            'msg' => 'error',
        ];
        if(!isset($post_data['apply_id'])){
            return json($return_data);
        }

        $db_data = FriendApply::field('apply_user_id,content,action,from,time')
            ->where([
                'id' => $post_data['apply_id']
            ])
            ->select()
            ->toArray();
        if(count($db_data) == 0){
            $return_data['msg'] = '没有这条申请数据';
            return json($return_data);
        }
        $db_data[0]['apply_user_id'] *= 1;
        if($db_data[0]['action']){
            $return_data['msg'] = '已经操作过这条数据了';
            return json($return_data);
        }

        $friend_data = Friend::where([
            'user_id' => USER_ID,
            'friend_id' => $db_data[0]['apply_user_id'],
        ])
            ->select()
            ->toArray();
        if(count($friend_data)){
            $return_data['msg'] = '对方已经是你的好友了';
            return json($return_data);
        }

        if($db_data[0]['apply_user_id'] == USER_ID){
            $return_data['msg'] = '你不能添加自己为好友';
            return json($return_data);
        }

        // 这里是我把对方删除，对方重新添加我
        $friend_data_obj = Friend::field('id')
            ->where([
                'user_id' => $db_data[0]['apply_user_id'],
                'friend_id' => USER_ID,
            ])
            ->find();
        $chat_user_ids = [ USER_ID,$db_data[0]['apply_user_id'] ];
        sort($chat_user_ids);
        $chat_user_ids = json_encode($chat_user_ids);
        if($friend_data_obj){
            $list_data_obj = ChatList::field('list_id')
                ->where([
                    'user_id' => $db_data[0]['apply_user_id'],
                    'user_ids' => $chat_user_ids,
                ])
                ->find();
            $list_id = $list_data_obj->list_id;
        }else{
            $list_id = md5(uniqid('JWT',true) . rand(1, 100000));
        }

        FriendApply::update([
            'id' => $post_data['apply_id'],
            'action' => 1,
        ]);
        /** 增加会话列表 */
        ChatList::create([
            'user_id' => USER_ID,
            'list_id' => $list_id,
            'user_ids' => $chat_user_ids,
            'type' => 0,
        ]);

        /** 增加到好友表 */
        Friend::create([
            'user_id' => USER_ID,
            'friend_id' => $db_data[0]['apply_user_id'],
            'from' => $db_data[0]['from'],
        ]);

        if(!$friend_data_obj){
            /** 增加会话列表 */
            ChatList::create([
                'user_id' => $db_data[0]['apply_user_id'],
                'list_id' => $list_id,
                'user_ids' => $chat_user_ids,
                'type' => 0,
            ]);
            /** 增加到成员表 */
            ChatMember::create([
                'list_id' => $list_id,
                'user_id' => $db_data[0]['apply_user_id'],
            ]);
            ChatMember::create([
                'list_id' => $list_id,
                'user_id' => USER_ID,
            ]);
            /** 增加到好友表 */
            Friend::create([
                'user_id' => $db_data[0]['apply_user_id'],
                'friend_id' => USER_ID,
                'from' => $db_data[0]['from'],
            ]);
        }
        /** 增加到对话表 */

        /** 有申请内容才写入对话 */
        if($db_data[0]['content']){
            Chat::create([
                'list_id' => $list_id,
                'user_id' => $db_data[0]['apply_user_id'],
                'content_type' => 0,
                'msg_type' => 0,
                'content' => [
                    'text' => $db_data[0]['content'],
                ],
                'time' => $db_data[0]['time'],
            ]);
        }

        Chat::create([
            'list_id' => $list_id,
            'user_id' => USER_ID,
            'content_type' => 0,
            'msg_type' => 0,
            'content' => [
                'text' => '我通过了你的朋友验证请求,现在我们可以开始聊天了',
            ],
            'time' => time(),
        ]);

        /** 通知双方重新获取会话列表和通讯录数据 */
        SendData::sendToUid(USER_ID, 'getChatList');
        SendData::sendToUid(USER_ID, 'getFriendList');
        SendData::sendToUid($db_data[0]['apply_user_id'],'getChatList');
        SendData::sendToUid($db_data[0]['apply_user_id'],'getFriendList');

        $return_data['err'] = 0;
        $return_data['msg'] = 'success';

        return json($return_data);
    }
}
